<?php

/**
 * ECSHOP 飞印接口函数库
 * ============================================================================
 * 版权所有 2005-2010
 * 网站地址: http://www.feyin.net；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: chenjunhui $
 * $Id: feyin.php 63 2010-11-15 11:25:46Z chenjunhui $
 */

include_once 'HttpClient.class.php';

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

define('MEMBER_CODE', getFeyin('feyin_code'));
define('FEYIN_KEY', getFeyin('feyin_API'));
define('FEYIN_HOST','my.feyin.net');
define('FEYIN_PORT', 80);
define('FEYIN_KEEP_ALIVE', False);

/*
 * 发送订单到飞印
 * 
 * @access	public
 * @param	array	$order			订单
 * @return	void
 */
function sendToFeyin($order) {
	if (!getFeyin('feyin_switch')) {
		return false;
	}
	if (checkIsOrder($order)) {
		/* 自由格式化订单内容 */
		if($order['count_numbers']>1){
		  $orderDetail .= '=============第'.($order['print_numbers']+1).'联============' . "\n";
		}else{
		  $orderDetail .= '==============================' . "\n";
		}
		$orderDetail .= '来自 ECSHOP 的订单' . "\n";
		$orderDetail .= ''.local_date($GLOBALS['_CFG']['time_format'], $order['confirm_time'])."\n" . 
						'订单：' . $order['order_sn'] . "\n" .  
						'姓名：' .$order['consignee'] . "\n" . 
						'电话：' . $order['tel'] . "\n" . 
						'手机：' . $order['mobile'] . "\n" . 
						'地址：' . $order['address'] . "\n" . 
						'------------------------------' . "\n"; 
	
		foreach ($order['goods'] as $goods) {
			$goods_attr = explode("\n", $goods['goods_attr']);
			array_pop($goods_attr);
			
			$orderDetail .= $goods['goods_name'] . "\n";

			if (!is_null($goods_attr[0])) {
				/* 商品单一属性 */
				if (count($goods_attr <= 1)) {
					$orderDetail .= $goods_attr[0] ."\n";
				} 
				
				/* 商品多个属性 */
				if (count($goods_attr) > 1) {
					array_shift($goods_attr);
					foreach ($goods_attr as $attr) {
						$orderDetail .= $attr . "\n";
					}
				}
			}
			
			$orderDetail .= '数量：' . $goods['goods_number'] . "\n";
			$orderDetail .= '                     ' . $goods['goods_price'] . "\n";
		}
 
		$orderDetail .= '------------------------------' . "\n" . 
						'合计：               ' . $order['surplus'] . "\n" . 
						'状态：' . $order['order_status'] . "\n" .  
						'支付方式：' . $order['pay_name'] . "\n" . 
						'应付款金额：' . $order['order_amount'] . "\n" . 
						'备注：' . $order['postscript'] . "\n\n" . 
						' 最佳配送时间：' . $order['best_time'] . "\n" .  
						' 如果没有指定商品，' . $order['how_oos'] . "\n";
		$orderDetail .= '==============================';

		$message = array(
			'memberCode' => MEMBER_CODE,
			'msgDetail' => $orderDetail,
			'deviceNo' => getFeyin('feyin_deviceNo'),
			'msgNo' => (time()+1).$order['print_numbers'],  //edit by 2011-4-18 credit
			//'msgNo' => (time()+1).MEMBER_CODE,
		);

		sendFreeMessage($message, $order);
	}
	unset($order);
}

/*
 * 以自由格式发送订单
 * 
 * @access	public
 * @param	array	$msg			订单内容
 * @return	void
 */
function sendFreeMessage($msg, $order) {
	$msg['reqTime'] = 1000*time();
	$content = $msg['memberCode'].$msg['msgDetail'].$msg['deviceNo'].$msg['msgNo'].$msg['reqTime'].FEYIN_KEY;
	$msg['securityCode'] = md5($content);
	$msg['mode']=2;

	return sendMessage($msg, $order);
}

/*
 * 以格式化内容发送订单
 * 
 * @access	public
 * @param	array	$msg			订单内容
 * @return	void
 */
function sendFormatedMessage($msgInfo) {
	$msgInfo['reqTime'] = 1000*time();
	$content = $msgInfo['memberCode'].$msgInfo['customerName'].$msgInfo['customerPhone'].$msgInfo['customerAddress'].$msgInfo['customerMemo'].$msgInfo['msgDetail'].$msgInfo['deviceNo'].$msgInfo['msgNo'].$msgInfo['reqTime'].FEYIN_KEY;

	$msgInfo['securityCode'] = md5($content);
	$msgInfo['mode']=1;
	
	return sendMessage($msgInfo);
}

/*
 * 发送订单
 * 
 * @access	public
 * @param	array	$msg			订单内容
 * @return	void
 */
function sendMessage($msgInfo, $order) {
	
	$client = new HttpClient(FEYIN_HOST,FEYIN_PORT);
	if(!$client->post('/api/sendMsg',$msgInfo)){ //提交失败
		return 'faild';
	}
	else{
		$res = $client->getContent();
		$order['confirm_time'] = sprintf($GLOBALS['_LANG']['confirm_time'], local_date($GLOBALS['_CFG']['time_format'], $order['confirm_time']));
		($res=='-1') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' Ip不允许，无法发送。;') : 
		($res=='-2') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 关键参数为空或请求方式不对，无法发送。;') : 
		($res=='-3') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 客户编码不对，无法发送。;') : 
		($res=='-4') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 安全校验码不正确，无法发送。;') : 
		($res=='-5') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 请求时间失效，无法发送。;') : 
		($res=='-6') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 订单内容格式不对，无法发送。;') : 
		($res=='-7') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 重复的消息，无法发送。;') : 
		($res=='-8') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 消息模式不对，无法发送。;') : 
		($res=='-9') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 服务器错误，无法发送。;') : 
		($res=='-10') ? insertFeyinLog($order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 服务器内部错误，无法发送。;') : 
		null;
		return $res;
	}
}

/*
 * 查询设备信息
 * 
 * @access	public
 * @return	void
 */
function listDevice(){
	$now = 1000*time();
	$client = new HttpClient(FEYIN_HOST,FEYIN_PORT);
	if(!$client->get('/api/listDevice?memberCode='.MEMBER_CODE.'&reqTime='.$now.'&securityCode='.md5(MEMBER_CODE.$now.FEYIN_KEY))){ //请求失败
		return 'faild';
	}
	else{
		return $client->getContent();
	}
}

/*
 * 查询异常消息
 * 
 * @access	public
 * @return	void
 */
function listException(){
	$now = 1000*time();
	$client = new HttpClient(FEYIN_HOST,FEYIN_PORT);
	if(!$client->get('/api/listException?memberCode='.MEMBER_CODE.'&reqTime='.$now.'&securityCode='.md5(MEMBER_CODE.$now.FEYIN_KEY))){ //请求失败
		return 'faild';
	}
	else{
		return $client->getContent();
	}
}

/*
 * 获取飞印设备状态
 * 
 * @access	public
 * @param	array		$deviceStatusXML
 * return	array		$status
 */
function getDevice($deviceStatusXML) {
	$device = (array)$deviceStatusXML;
	$device = $device['device'];

    if (count($deviceStatusXML) > 1) {
    	for ($i = 0; $i < count($device); $i++) {
		    $temp[$i] = (array)$device[$i];
        }
	
	    for ($j = 0; $j < count($temp); $j++) {
    		if ($temp[$j]['@attributes']['id']==getFeyin('feyin_deviceNo')) {
			    $devices = $temp[$j];
		    }
	    }
    } else {
        $devices = (array)$device;
    }
   if($devices){
	/* 状态数组删除 */
	array_shift($devices);  //删除数组中的第一个元素
    unset($devices['simCode']);
   }
	$devices['paperStatus'] = (array)$devices['paperStatus'];
    
    foreach ($devices['paperStatus'] as $value) { }
	$devices['paperStatus'] = $value;

	return $devices;
}

/*
 * 获取飞印相关信息
 * 
 * @access	public
 * @param	string		$info
 * @return	void
 */
function getFeyin($info){
	$sql = 'SELECT ' . $info . ' FROM ' . $GLOBALS['ecs']->table('feyin') . 
			' where feyin_id = "1"';
	$res = $GLOBALS['db']->getOne($sql);
	return $res;
}

/*
 * 检查订单是否存在
 * 
 * @access  public
 * @param   array  $order           订单
 * @return  void
 */
function checkIsOrder($order) {
	$sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('order_info') .
			' WHERE order_id = ' . $order['order_id'];
	$res = $GLOBALS['db']->query($sql);
	$before = $GLOBALS['db']->fetchRow($res);
	$row['before'] = $before;
	$row['after'] = $order;

	/* 检查数据库的订单 ID 和传入的订单号是否相同 */
	if ($before['order_id'] == $order['order_id'] && $before['order_sn'] == $order['order_sn']) {
		return checkOrderStatus($row);
	} else {
		$order['confirm_time'] = sprintf($GLOBALS['_LANG']['confirm_time'], local_date($GLOBALS['_CFG']['time_format'], $order['confirm_time']));
		$cause = $order['confirm_time'] . ' 的订单号：' . $order['order_sn'] . ' 不存在，或者未知错误。;';
		insertFeyinLog($cause);
		return false;
	}
}

/*
 * 检查订单状态是否已确认
 * 
 * @access  public
 * @param   array  $order           订单
 * @return  void
 */
function checkOrderStatus($row) {
	$before_order_status = $row['before']['order_status'];
	$after_order_status = $row['after']['order_status'];
	$before_pay_status = $row['before']['pay_status'];
	$after_pay_status = $row['after']['pay_status'];
	
	/* 检查订单是否 已确认 或者 已付款 状态 */
	if ($before_order_status == $after_order_status || $before_pay_status == $after_pay_status) {
		return true;
	} else {
		$row['after']['confirm_time'] = sprintf($GLOBALS['_LANG']['confirm_time'], local_date($GLOBALS['_CFG']['time_format'], $row['after']['confirm_time']));
		$cause = $row['after']['confirm_time'] . ' 的订单号：' . $row['order_sn'] . ' 未确认，或者是未付款状态。;';
		insertFeyinLog($cause);
		return false;
	}
}

/*
 * 记录错误日志
 * 
 * @access	public
 * @param	string	$cause			错误原因
 */
function insertFeyinLog($cause) {
	/* 取出之前的错误日志 */
	$sql = 'SELECT feyin_log FROM ' . $GLOBALS['ecs']->table('feyin') . 
			' WHERE feyin_id = "1"';
	$res = $GLOBALS['db']->query($sql);
	$before_log = $GLOBALS['db']->fetchRow($res);

	/* 把新的日志记录插进数据库 */
	$cause = $before_log['feyin_log'].$cause;
	$sql = 'UPDATE ' . $GLOBALS['ecs']->table('feyin') . 
			' SET feyin_log = "' . $cause . 
			'" WHERE feyin_id = "1"';
	$GLOBALS['db']->query($sql);
}
?>
